package com.atguigu.tingshu.common.login;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

@Aspect
@Component
@Slf4j
public class GuiGuLoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    // 环绕通知，应用于需要登录验证的方法
    // 该切面方法拦截的时com.atguigu.tingshu包下所有api接口中的所有方法，并且方法上需要有@tsLogin注解
    /*
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(tsLogin)")
    public Object login(ProceedingJoinPoint joinPoint, TsLogin tsLogin) throws Throwable {
        try {
            // 获取当前请求的HttpServletRequest对象
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            // 从请求头中获取token
            String token = request.getHeader("token");

            // 如果注解tsLogin的required属性为true，则进行登录验证
            if (tsLogin.required()) {
                // 如果token为空，则抛出登录认证异常
                if (StringUtils.isEmpty(token)) {
                    throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }
                // 根据token从Redis中获取用户信息
                String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(loginKey);
                // 如果用户信息为空，则抛出登录认证异常
                if (null == userInfo) {
                    throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }
            }

            // 如果token不为空，则获取用户信息并设置用户ID到AuthContextHolder中
            if (!StringUtils.isEmpty(token)) {
                String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(loginKey);
                if (null != userInfo) {
                    AuthContextHolder.setUserId(userInfo.getId());
                }
            }

            // 执行被拦截的方法
            return joinPoint.proceed();
        } finally {
            // 移除AuthContextHolder中的用户ID，避免内存泄漏
            AuthContextHolder.removeUserId();
        }
    }*/
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(tsLogin)")
    public Object login(ProceedingJoinPoint joinPoint, TsLogin tsLogin) throws Throwable {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (tsLogin.required()) {
                if (StringUtils.isEmpty(token)) {
                    throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }
                String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(loginKey);
                if (null == userInfo) {
                    throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }
            }
            if (!StringUtils.isEmpty(token)) {
                String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(loginKey);
                if (null != userInfo) {
                    AuthContextHolder.setUserId(userInfo.getId());
                }
            }
            return joinPoint.proceed();
        } finally {
            AuthContextHolder.removeUserId();
        }
    }
}
